package thread;

public class SyncDemo {
    public static void main(String[] args) {
        Table table = new Table();
        Thread t1=new Thread("a"){
            @Override
            public void run() {
                while (true){
                    int bean=table.getBeans();
                    Thread.yield();
                    System.out.println(getName()+bean);
                }
            }
        };
        Thread t2=new Thread("b"){
            @Override
            public void run() {
                while (true){
                    int bean=table.getBeans();
                    Thread.yield();
                    System.out.println(getName()+bean);
                }
            }
        };
        t1.start();
        t2.start();
    }
}
class Table{
    private int beans=20;

    public synchronized int getBeans(){//synchronized同一时刻只有一个线程在方法内部执行
        if (beans==0){
            throw new RuntimeException("没有豆子");
        }
        Thread.yield();//让运行该方法的线程主动放弃本次剩余时间片

        return beans--;
    }
}